package com.wolfalpha.utron.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.umeng.analytics.MobclickAgent;
import com.wolfalpha.utron.R;
import com.wolfalpha.utron.app.AppContext;
import com.wolfalpha.utron.app.AppManager;
import com.wolfalpha.utron.bean.UserInfo;
import com.wolfalpha.utron.exception.LoginException;
import com.wolfalpha.utron.service.UserService;
import com.wolfalpha.utron.service.impl.UserServiceImpl;
import com.wolfalpha.utron.ui.UIHelper;
import com.wolfalpha.utron.utils.ImageUtils;
import com.wolfalpha.utron.utils.ThreadPoolUtils;

import java.io.IOException;

/**
 * 登录
 *
 * @author luodon
 */
public class LoginActivity extends Activity implements View.OnClickListener {

    //LOGO图片
    private ImageView ivLogo;
    //账号
    private EditText etAccount;
    //密码
    private EditText etPwd;
    //登录按钮
    private Button btnLogin;
    //忘记密码
    private TextView tvForgetPwd;
    //注册
    private TextView tvSignUp;
    //匿名登录
    private TextView tvAnonLogin;

    private UserService userService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        loadPropertises();

        setContentView(R.layout.activity_login);
        userService = new UserServiceImpl();
        initView();
        initListeners();
    }

    private void loadPropertises() {
        if (AppContext.getInstance().getIsLogined()) {
            handler.sendEmptyMessage(LOGIN_FAST);
        }
    }

    private UserInfo userInfo = null;

    private final static int ANON_LOGIN = 4;    //匿名登录
    private final static int LOGIN = 3;         //正常登录
    private final static int LOGIN_FAST = 2;    //快速登录      在InitActivity中实现

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case ANON_LOGIN:
                    //匿名登录
//                    ThreadPoolUtils.execute(new Runnable() {
//                        @Override
//                        public void run() {
//                            userService.anonLogin("android", String.valueOf(AppContext.getSDKVersion()), AppContext.getInstance().getAppVersionCode());
//                            /**
//                             * 登录环信
//                             */
//                            //调用sdk登陆方法登陆聊天服务器
//                            EMChatManager.getInstance().login("-1", "-1", new EMCallBack() {
//                                //
//                                @Override
//                                public void onSuccess() {
//                                    // TODO Auto-generated method stub
//                                    AppContext.getInstance().setProperty("logined", "true");
//                                    AppContext.getInstance().initializeContacts();
//                                    AppContext.getInstance().doAnonLogin();
//                                    EMChat.getInstance().setAutoLogin(true);
//                                    AppManager.getAppManager().finishOActivity();
//                                    UIHelper.showActivityAndFinish(LoginActivity.this, MainActivity.class);
//                                }
//
//                                @Override
//                                public void onProgress(int progress, String status) {
//                                    // TODO Auto-generated method stub
//                                }
//
//                                @Override
//                                public void onError(int code, String message) {
//                                    // TODO Auto-generated method stub
//                                    UIHelper.ToastMessage(LoginActivity.this, "登录失败");
//                                }
//                            });
//                        }
//                    });
                    break;
                case LOGIN:
                    final String account = etAccount.getText().toString().trim();
                    final String pwd = etPwd.getText().toString().trim();
                    //登录
                    final ProgressDialog pd = new ProgressDialog(LoginActivity.this);
                    pd.setMessage("正在登陆");
                    pd.setCancelable(false);
                    pd.show();
                    ThreadPoolUtils.execute(new Runnable() {
                        @Override
                        public void run() {

                            try {
                                userInfo = userService.login(account, pwd);
                            } catch (final LoginException e) {
                                e.printStackTrace();
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        pd.dismiss();
                                        UIHelper.ToastMessage(LoginActivity.this, e.getMessage());
                                        btnLogin.setClickable(true);
                                    }
                                });
                                return;
                            }
                            if (userInfo != null) {
                                Bitmap bitmap = userService.getUserHead(userInfo.getHead_pic());
                                try {
                                    if (bitmap != null) {
                                        ImageUtils.saveImage(AppContext.getInstance(), "head_pic.jpg", bitmap);
                                    } else {
                                        ImageUtils.saveImage(AppContext.getInstance(), "head_pic.jpg", BitmapFactory.decodeResource(LoginActivity.this.getResources(), R.mipmap.head_default));
                                    }
                                } catch (IOException e) {
                                    try {
                                        ImageUtils.saveImage(AppContext.getInstance(), "head_pic.jpg", BitmapFactory.decodeResource(LoginActivity.this.getResources(), R.mipmap.head_default));
                                    } catch (IOException e1) {
                                        e1.printStackTrace();
                                    }
                                    e.printStackTrace();
                                }
                                /**
                                 * 登录环信
                                 */
                                //调用sdk登陆方法登陆聊天服务器
                                EMChatManager.getInstance().login("" + userInfo.getUser_id(), pwd, new EMCallBack() {
                                    //
                                    @Override
                                    public void onSuccess() {
                                        // TODO Auto-generated method stub
                                        AppContext.getInstance().setProperty("utron_account", account);
                                        AppContext.getInstance().setProperty("utron_pwd", pwd);
                                        AppContext.getInstance().doLogin();
                                        AppContext.getInstance().initUserInfo(userInfo);
                                        AppContext.getInstance().setProperty("logined", "true");
                                        AppContext.getInstance().initializeContacts();
                                        EMChat.getInstance().setAutoLogin(true);
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                pd.dismiss();
                                                UIHelper.ToastMessage(LoginActivity.this, "登录成功");
                                            }
                                        });
                                        AppManager.getAppManager().finishOActivity();
                                        UIHelper.showActivityAndFinish(LoginActivity.this, MainActivity.class);
                                    }

                                    @Override
                                    public void onProgress(int progress, String status) {
                                        // TODO Auto-generated method stub
                                    }

                                    @Override
                                    public void onError(int code, String message) {
                                        // TODO Auto-generated method stub
                                        System.out.println(message);
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                pd.dismiss();
                                                UIHelper.ToastMessage(LoginActivity.this, "登录失败");
                                                btnLogin.setClickable(true);
                                            }
                                        });
                                    }
                                });

                            } else {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        pd.dismiss();
                                        UIHelper.ToastMessage(LoginActivity.this, "无用户信息,请先注册");
                                        btnLogin.setClickable(true);
                                    }
                                });
                            }
                        }
                    });
                    break;
                case LOGIN_FAST:
                    //快速登录
//                    ThreadPoolUtils.execute(new Runnable() {
//                        @Override
//                        public void run() {
//                            String account = AppContext.getInstance().getProperty("utron_account");
//                            String pwd = AppContext.getInstance().getProperty("utron_pwd");
//                            UserBaseInfo userBaseInfo = userService.login(account, pwd);
//                            if (userBaseInfo != null) {
//                                UIHelper.showActivityAndFinish(LoginActivity.this, MainActivity.class);
//                            }
//                        }
//                    });
//                    UIHelper.showActivityAndFinish(LoginActivity.this, MainActivity.class);
                    break;
            }
        }
    };

    /**
     * 初始化界面
     */
    private void initView() {
        etAccount = (EditText) findViewById(R.id.et_acc);
        etPwd = (EditText) findViewById(R.id.et_pwd);
        btnLogin = (Button) findViewById(R.id.btn_login);
        tvForgetPwd = (TextView) findViewById(R.id.tv_forget_pwd);
        tvSignUp = (TextView) findViewById(R.id.tv_signup);
        tvAnonLogin = (TextView) findViewById(R.id.tv_anon_login);
        ivLogo = (ImageView) findViewById(R.id.iv_logo);
    }

    /**
     * 初始化监听
     */
    private void initListeners() {
        tvSignUp.setOnClickListener(this);
        tvForgetPwd.setOnClickListener(this);
        tvAnonLogin.setOnClickListener(this);
        btnLogin.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_signup:
                //注册
                UIHelper.showActivityAndFinish(LoginActivity.this, RegisterActivity.class);
                break;
            case R.id.btn_login:
                //登录
                btnLogin.setClickable(false);
                if (!TextUtils.isEmpty(etAccount.getText().toString().trim()) && !TextUtils.isEmpty(etPwd.getText().toString().trim())) {
                    handler.sendEmptyMessage(LOGIN);
                } else {
                    UIHelper.ToastMessage(LoginActivity.this, "请先输入账号和密码");
                    btnLogin.setClickable(true);
                }
                break;
            case R.id.tv_anon_login:
                //匿名登录
                tvAnonLogin.setClickable(false);
                handler.sendEmptyMessage(ANON_LOGIN);
                break;
        }
    }

    public void onResume() {
        super.onResume();
        //友盟统计
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        //友盟统计
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
}
